from flask import Blueprint, request, Response, render_template, current_app, jsonify
from .utils import rate_limit, validate_input, APIError, generate_conversation_title
from .models import Conversation
import logging

logger = logging.getLogger(__name__)
main = Blueprint('main', __name__)

@main.route('/')
def index():
    """主页路由"""
    return render_template('index.html')

@main.route('/api/conversations', methods=['GET', 'POST'])
@rate_limit()
def conversations():
    """会话管理路由"""
    try:
        manager = current_app.config.get('CONVERSATION_MANAGER')
        if not manager:
            logger.error("Conversation manager not initialized")
            raise APIError("Server configuration error", status_code=500)

        if request.method == 'POST':
            # 创建新对话
            conversation = manager.create_conversation(title="新对话")
            logger.info(f"Created new conversation: {conversation.conversation_id}")
            manager.save_to_file(current_app.config['CONVERSATIONS_FILE'])
            return jsonify(conversation.to_dict()), 201
        else:
            # 获取所有对话基本信息
            return jsonify(manager.get_all_conversations())
    except Exception as e:
        logger.error(f"Error in conversations endpoint: {str(e)}")
        raise APIError(str(e))

@main.route('/api/conversations/<conversation_id>', methods=['GET', 'DELETE'])
@rate_limit()
def conversation(conversation_id):
    """单个对话操作"""
    try:
        manager = current_app.config.get('CONVERSATION_MANAGER')
        if not manager:
            raise APIError("Server configuration error", status_code=500)

        if request.method == 'GET':
            conv = manager.get_conversation(conversation_id)
            if not conv:
                raise APIError("Conversation not found", status_code=404)
            return jsonify(conv.to_dict())

        elif request.method == 'DELETE':
            if manager.delete_conversation(conversation_id):
                manager.save_to_file(current_app.config['CONVERSATIONS_FILE'])
                return jsonify({"message": "Conversation deleted successfully"})
            raise APIError("Conversation not found", status_code=404)

    except Exception as e:
        logger.error(f"Error handling conversation {conversation_id}: {str(e)}")
        raise APIError(str(e))

@main.route('/api/chat', methods=['POST'])
@rate_limit()
def chat():
    """聊天接口（流式）"""
    try:
        if not request.is_json:
            raise APIError("请求必须是JSON格式")
            
        data = request.get_json()
        if not data or 'message' not in data:
            raise APIError("无效的请求数据")

        message = data['message']
        conversation_id = data.get('conversation_id')

        is_valid, error_msg = validate_input(message)
        if not is_valid:
            raise APIError(error_msg)

        app = current_app._get_current_object()
        manager = app.config.get('CONVERSATION_MANAGER')
        if not manager:
            raise APIError("Server configuration error", status_code=500)

        conversation = None
        if conversation_id:
            conversation = manager.get_conversation(conversation_id)
        if not conversation:
            conversation = manager.create_conversation(title="新对话")
            conversation_id = conversation.conversation_id

        messages = [{"role": "system", "content": app.config['SYSTEM_PROMPT']}]
        for msg in conversation.messages:
            messages.append({"role": msg.role, "content": msg.content})
        messages.append({"role": "user", "content": message})

        # 使用当前模型进行对话
        current_model_name = app.config['MODEL_NAME']

        def generate():
            try:
                with app.app_context():
                    from openai import OpenAI
                    client = OpenAI(
                        api_key=app.config['DASHSCOPE_API_KEY'],
                        base_url=app.config['API_BASE_URL']
                    )

                    completion = client.chat.completions.create(
                        model=current_model_name,
                        messages=messages,
                        stream=True,
                        stream_options={"include_usage": True}
                    )
                    
                    full_response = ""
                    for chunk in completion:
                        if chunk.choices and chunk.choices[0].delta.content is not None:
                            content = chunk.choices[0].delta.content
                            full_response += content
                            yield content

                    # 流结束后更新对话数据并保存
                    conversation.add_message(message, "user")
                    conversation.add_message(full_response, "assistant")

                    # 生成标题（仅使用消息内容）
                    all_messages_text = "\n".join([m.content for m in conversation.messages])
                    new_title = generate_conversation_title(all_messages_text, 50)
                    conversation.title = new_title

                    manager.save_to_file(app.config['CONVERSATIONS_FILE'])

            except Exception as e:
                logger.error(f"API error in generate: {str(e)}")
                yield "\n抱歉，服务暂时不可用，请稍后重试。"

        return Response(
            generate(),
            content_type='text/event-stream',
            headers={
                'Cache-Control': 'no-cache',
                'X-Accel-Buffering': 'no'
            }
        )

    except APIError as e:
        return jsonify({"error": "API Error", "message": str(e)}), e.status_code
    except Exception as e:
        logger.error(f"Error in chat endpoint: {str(e)}")
        return jsonify({"error": "Internal server error", "message": "服务器内部错误"}), 500

@main.route('/api/conversations/<conversation_id>/export', methods=['GET'])
@rate_limit()
def export_conversation(conversation_id):
    """导出对话记录"""
    try:
        manager = current_app.config.get('CONVERSATION_MANAGER')
        if not manager:
            raise APIError("Server configuration error", status_code=500)

        conversation = manager.get_conversation(conversation_id)
        if not conversation:
            raise APIError("Conversation not found", status_code=404)

        export_data = conversation.to_dict()
        return jsonify(export_data)

    except Exception as e:
        logger.error(f"Error exporting conversation {conversation_id}: {str(e)}")
        raise APIError(str(e))

@main.route('/api/models', methods=['GET'])
@rate_limit()
def get_models():
    """获取可用模型列表和当前模型"""
    try:
        app = current_app._get_current_object()
        available_models = app.config['AVAILABLE_MODELS']
        current_model = app.config['MODEL_NAME']
        return jsonify({
            "available_models": available_models,
            "current_model": current_model
        })
    except Exception as e:
        logger.error(f"Error in get_models: {str(e)}")
        raise APIError(str(e))

@main.route('/api/models', methods=['POST'])
@rate_limit()
def set_model():
    """设置当前使用的模型"""
    try:
        data = request.get_json()
        if not data or 'model_name' not in data:
            raise APIError("Invalid model_name")

        model_name = data['model_name']
        app = current_app._get_current_object()
        if model_name not in app.config['AVAILABLE_MODELS']:
            raise APIError("Model not found", status_code=404)

        app.config['MODEL_NAME'] = model_name
        return jsonify({"message": "Model updated successfully"})
    except APIError as e:
        return jsonify({"error": e.message}), e.status_code
    except Exception as e:
        logger.error(f"Error in set_model: {str(e)}")
        raise APIError(str(e))
